import { createApp } from "vue";
import { createPinia } from "pinia";
import App from "./App.vue";
import router from "./router";
import "./styles/tailwind.scss";

// 引入 Element Plus
import ElementPlus from "element-plus";
import "element-plus/dist/index.css";
// 确保深色模式 CSS 在其他样式之后引入
import "element-plus/theme-chalk/dark/css-vars.css";
import * as ElementPlusIconsVue from "@element-plus/icons-vue";
import zhCn from "element-plus/dist/locale/zh-cn.mjs";

// 引入 Arco Design
import ArcoVue from "@arco-design/web-vue";
import "@arco-design/web-vue/dist/arco.css";

// 引入全局样式
import "./styles/global.scss";
// 引入 Element Plus 深色模式样式覆盖
import "./styles/element-dark.scss";

// 引入全局错误处理
import { setupGlobalErrorHandling, vueErrorHandler } from "@/utils/errorHandler";
import { useUserStore } from "@/stores/user";
import { useNotificationStore } from "@/stores/notification";
import { watch } from "vue";

// 在Vue应用初始化之前拦截错误通知
if (typeof window !== 'undefined') {
  // 禁用错误通知系统
  const disableErrorNotifications = () => {
    // 添加全局CSS隐藏样式
    const style = document.createElement('style');
    style.textContent = `
      .el-notification[role="alert"],
      .el-message--error,
      .el-message-box__wrapper,
      .el-overlay.is-message-box,
      div[role="alert"][class*="error"],
      [aria-live="assertive"][class*="error"] {
        display: none !important;
        visibility: hidden !important;
        opacity: 0 !important;
        pointer-events: none !important;
      }
    `;
    document.head.appendChild(style);
    
    // 替换通知方法
    if (window.ELEMENT) {
      ['Notification', 'Message', 'MessageBox'].forEach(method => {
        if (window.ELEMENT[method]) {
          const original = window.ELEMENT[method];
          window.ELEMENT[method] = function(options) {
            // 过滤错误通知
            if (options && (
                options.type === 'error' || 
                (options.title && options.title.includes('错误')) ||
                (options.message && (
                  options.message.includes('错误') || 
                  options.message.includes('null') ||
                  options.message.includes('应用错误')
                ))
              )) {
              console.log('已阻止错误通知:', options);
              return { close: () => {} };
            }
            return original.apply(this, arguments);
          };
        }
      });
    }
  };
  
  // 执行拦截
  disableErrorNotifications();
  
  // 监听DOMContentLoaded事件，确保页面加载时执行
  document.addEventListener('DOMContentLoaded', disableErrorNotifications);
  
  // 定期移除错误通知
  setInterval(() => {
    const errorElements = document.querySelectorAll('.el-notification[role="alert"], .el-message--error');
    errorElements.forEach(el => {
      const text = el.textContent || '';
      if (text.includes('错误') || text.includes('Error') || text.includes('null') || text.includes('应用')) {
        el.style.display = 'none';
        if (el.parentNode) {
          el.parentNode.removeChild(el);
        }
      }
    });
  }, 100);
}

const app = createApp(App);
const pinia = createPinia();

// 设置全局错误处理
app.config.errorHandler = vueErrorHandler;
setupGlobalErrorHandling();

// 注册 Element Plus 图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component);
}

app.use(pinia);
app.use(router);
app.use(ElementPlus, {
  locale: zhCn,
});
app.use(ArcoVue);

// 监听用户登录和登出事件，处理通知初始化和销毁
const handleUserStateChange = () => {
  const userStore = useUserStore();
  const notificationStore = useNotificationStore();

  // 监听用户登录事件
  watch(() => userStore.isLoggedIn, (isLoggedIn) => {
    if (isLoggedIn) {
      // 用户登录，初始化通知模块
      notificationStore.initialize();
    } else {
      // 用户登出，重置通知模块
      notificationStore.reset();
    }
  }, { immediate: true });
};

// 在应用启动后执行
handleUserStateChange();

app.mount("#app");
